package teamproject.visualization.gui.behaviors;

import java.util.Enumeration;

import javax.media.j3d.Bounds;
import javax.media.j3d.Transform3D;
import javax.media.j3d.TransformGroup;
import javax.vecmath.Point3f;
import javax.vecmath.Vector3d;

import teamproject.visualization.gui.VisualObjectContainer;
import teamproject.visualization.gui.visualobjects.Package;

import com.sun.j3d.utils.geometry.Box;

/**
 * Describes the moving behaviour for one packet.
 */
public class PackageEdgeBehavior implements Resettable {

	private TransformGroup target;
	private Transform3D transform = new Transform3D();
	private Vector3d translateVector = new Vector3d();
	private boolean started = false; // has a packet started moving
	private int hopCounter = 1; // how often has a packet moved
	private int id;
	private float edgeLength;
	private Package packet;
	private VisualObjectContainer container = VisualObjectContainer
			.getInstance();
	float distance;
	private Vector3d tempVector = new Vector3d();
	private Transform3D tempTransform = new Transform3D();
	private Enumeration<Object> children;
	private Object obj;
	private Box box = null;
	private Point3f lastPoint = new Point3f();

	public PackageEdgeBehavior(TransformGroup target, Bounds bounds,
			Package packet, float edgeLength, float distance, int id) {
		this.target = target;
		this.packet = packet;
		this.setId(id);
		this.edgeLength = edgeLength;
		this.distance = distance;
	}

	protected void doProcess() {

		if (container.isPackageVisible()) {
			packet.setAnimatedVisible(true);
			packet.setVisible(true);
		}

		if (hopCounter > edgeLength / distance) {
			packet.setAnimatedVisible(false);
			packet.setVisible(false);
			setStarted(false);
		} else {
			translateVector.x = distance * hopCounter;
			translateVector.y = 0;
			translateVector.z = 0;

			transform.setTranslation(translateVector);
			target.setTransform(transform);
			hopCounter++;
		}
	}

	public Point3f getCurrentPacketPosition() {
		children = target.getAllChildren();
		while (children.hasMoreElements()) {
			obj = children.nextElement();
			if (obj instanceof Box)
				box = (Box) obj;
		}

		box.getLocalToVworld(tempTransform);
		tempTransform.get(tempVector);

		lastPoint.x = (float) tempVector.x;
		lastPoint.y = (float) tempVector.y;
		lastPoint.z = (float) tempVector.z;
		return lastPoint;
	}

	public int getId() {
		return id;
	}

	public boolean hasStarted() {
		return started;
	}

	@Override
	public void reset() {
		started = false;
		hopCounter = 1;

		packet.setVisible(false);

		translateVector.x = 0;
		translateVector.y = 0;
		translateVector.z = 0;

		transform.setTranslation(translateVector);
		target.setTransform(transform);
	}

	public void setId(int id) {
		this.id = id;
	}

	public void setStarted(boolean started) {
		this.started = started;
		if (started) {

		}
	}
}
